package com.kly.controller;

import com.kly.common.ErrorCode;
import com.kly.common.Result;
import com.kly.common.UserContext;
import com.kly.exception.BusinessException;
import com.kly.model.domain.Team;
import com.kly.model.domain.UserTeam;
import com.kly.model.dto.JoinTeamDto;
import com.kly.model.dto.TeamDto;
import com.kly.model.dto.TeamQuery;
import com.kly.model.vo.PageResult;
import com.kly.model.vo.TeamVo;
import com.kly.service.TeamService;
import com.kly.service.UserTeamService;
import lombok.RequiredArgsConstructor;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 队伍控制器
 *
 * @author admin
 * @date 2025/2/24
 */

@RestController
@RequestMapping("/team")
@RequiredArgsConstructor
// @CrossOrigin(origins = "http://localhost:5173", allowedHeaders = "true")
public class TeamController {

    private final TeamService teamService;

    private final UserTeamService userTeamService;


    // restful 风格

    /**
     * 创建队伍
     */


    /**
     * 根据id查询队伍
     */
    @GetMapping("/{id}")
    public Result<Team> getTeamById(@PathVariable("id") Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return Result.success(team);
    }


    /**
     * 删除队伍
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteTeam(@PathVariable("id") Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return Result.success(teamService.deleteTeam(id));
    }


    /**
     * 更新队伍
     */
    @PutMapping
    public Result<Boolean> updateTeam(@RequestBody TeamDto teamDto) {
        if(teamDto == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Boolean update = teamService.updateTeam(teamDto);
        return Result.success(update);
    }


    /**
     * 搜索队伍
      */
    @GetMapping("/list")
    public Result<List<Team>> searchTeams() {
        return Result.success(teamService.list());
    }

    /**
     * 搜索队伍 分页
     */
    @GetMapping("/list/page")
    public Result<PageResult<TeamVo>> searchTeamsByPage(TeamQuery teamQuery) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        PageResult<TeamVo> pageResult = teamService.searchTeamsByPage(teamQuery, true);

        return Result.success(pageResult);
    }


    /**
     * 用户加入队伍
     */
    @PostMapping("/join")
    public Result<Boolean> joinTeam(@RequestBody JoinTeamDto joinTeamDto) {
        // 短时间大量请求 仍会发生加入队伍出错 synchronized
        // 采用 synchronized解决
        if (joinTeamDto == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        return Result.success(teamService.joinTeam(joinTeamDto));
    }


    /**
     * 用户退出队伍
     */
    @PostMapping("/quit")
    public Result<Boolean> quitTeam(@RequestBody JoinTeamDto joinTeamDto) {
        if (joinTeamDto == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        return Result.success(teamService.quitTeam(joinTeamDto));
    }



    @PostMapping("/add")
    public Result<Long> createTeam(@RequestBody TeamDto teamDto) {
        if (teamDto == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Long id = teamService.createTeam(teamDto);
        return Result.success(id);
    }


    /**
     * 获取我创建的队伍
     */
    @GetMapping("/list/create")
    public Result<PageResult<TeamVo>> listMyCreateTeams(TeamQuery teamQuery) {
        Long id = UserContext.getUser().getId();
        if (id == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        teamQuery.setUserId(id);

        return Result.success(teamService.searchTeamsByPage(teamQuery, false));
    }


    /**
     * 获取我加入的队伍
     */
    @GetMapping("/list/join")
    public Result<PageResult<TeamVo>> listMyJoinTeams(TeamQuery teamQuery) {
        Long id = UserContext.getUser().getId();
        if (id == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        // 查询队伍id
        List<UserTeam> userTeamList = userTeamService.lambdaQuery()
                .eq(UserTeam::getUserId, id)
                .list();
        if(CollectionUtils.isEmpty(userTeamList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "未加入队伍");
        }

        List<Long> teamIds = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toList());
        teamQuery.setTeamIdList(teamIds);
        return Result.success(teamService.searchTeamsByPage(teamQuery, false));
    }


    /**
     * 查询用户是否在队伍中
     */
    @GetMapping("/in/{id}")
    public Result<Boolean> isJoinTeam(@PathVariable("id") Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = UserContext.getUser().getId();
        if (userId == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        UserTeam userTeam = userTeamService.lambdaQuery()
                .eq(UserTeam::getUserId, userId)
                .eq(UserTeam::getTeamId, id)
                .one();
        return Result.success(userTeam != null);
    }

}
